package com.innovation.ic.im.end.base.service.im_erp9.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.base.Strings;
import com.innovation.ic.b1b.framework.manager.RedisManager;
import com.innovation.ic.im.end.base.mapper.im_erp9.*;
import com.innovation.ic.im.end.base.model.im_erp9.*;
import com.innovation.ic.im.end.base.pojo.ServiceResult;
import com.innovation.ic.im.end.base.pojo.constant.*;
import com.innovation.ic.im.end.base.pojo.enums.AccountIntegrationEnum;
import com.innovation.ic.im.end.base.pojo.im_erp9.AccountFindLastContactResultPojo;
import com.innovation.ic.im.end.base.pojo.im_erp9.AccountGroupLastContactPojo;
import com.innovation.ic.im.end.base.pojo.im_erp9.GroupPojo;
import com.innovation.ic.im.end.base.handler.helper.HandlerHelper;
import com.innovation.ic.im.end.base.handler.im_erp9.WebSocketHandler;
import com.innovation.ic.im.end.base.pojo.im_erp9.ScAccountFindLastContactResultPojo;
import com.innovation.ic.im.end.base.service.im_erp9.UserGroupService;
import com.innovation.ic.b1b.framework.util.DateUtils;
import com.innovation.ic.im.end.base.value.config.RedisParamConfig;
import com.innovation.ic.im.end.base.value.config.SystemConfig;
import com.innovation.ic.im.end.base.vo.im_erp9.UserGroupVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.util.*;

/**
 * UserGroup的具体实现类
 */
@Service
@Transactional
public class UserGroupServiceImpl extends ServiceImpl<UserGroupMapper, UserGroup> implements UserGroupService {
    private static final Logger log = LoggerFactory.getLogger(UserGroupServiceImpl.class);

    @Resource
    private UserGroupMapper userGroupMapper;

    @Resource
    private SystemConfig systemConfig;

    @Resource
    private AccountMapper accountMapper;

    @Resource
    private CustomerServiceScoreMapper customerServiceScoreMapper;

    @Resource
    private GroupMapper groupMapper;

    @Resource
    private RefUserGroupAccountMapper refUserGroupAccountMapper;

    @Resource
    private RedisParamConfig redisParamConfig;

    @Resource
    private RedisManager redisManager;

    /**
     * 获取最近一对一、群组的联系人数据。按置顶顺序降序排列，按最后聊天时间降序排列。显示未读消息数量
     * @param account 账号
     * @return 返回近期的联系人数据
     */
    @Override
    public ServiceResult<List<AccountGroupLastContactPojo>> findRedisLastContact(String account) {
        ServiceResult<List<AccountGroupLastContactPojo>> serviceResult = new ServiceResult<>();

        // 从redis中获取最近联系人数据
        List<AccountGroupLastContactPojo> resultList = new ArrayList<>();
        String lastContact = (String) redisManager.get(RedisStorage.USER_GROUP_CURRENT_PREFIX + account);
        JSONArray jsonArray = (JSONArray) JSONObject.parse(lastContact);
        if(jsonArray != null && !jsonArray.isEmpty()){
            resultList = JSONObject.parseArray(jsonArray.toJSONString(), AccountGroupLastContactPojo.class);

            // 如果type字段值为6、7、8，需要修改消息内容为固定值
            if(resultList != null && resultList.size() > 0){
                for(AccountGroupLastContactPojo accountGroupLastContactPojo : resultList){
                    String fixMessage = getFixMessageByMessageType(accountGroupLastContactPojo.getType());
                    if(!Strings.isNullOrEmpty(fixMessage)){
                        accountGroupLastContactPojo.setLastMessage(fixMessage);
                    }
                }
            }
        }

        serviceResult.setMessage(ServiceResult.SELECT_SUCCESS);
        serviceResult.setSuccess(Boolean.TRUE);
        serviceResult.setResult(resultList);
        return serviceResult;
    }

    /**
     * 从redis中获取供应商协同账号的近期联系人
     * @param account 账号
     * @return 返回查询结果
     */
    @Override
    public ServiceResult<List<ScAccountFindLastContactResultPojo>> findRedisScRecentContact(String account) {
        ServiceResult<List<ScAccountFindLastContactResultPojo>> serviceResult = new ServiceResult<>();

        // 从redis中获取最近联系人数据
        List<ScAccountFindLastContactResultPojo> resultList = new ArrayList<>();
        String lastContact = (String) redisManager.get(RedisStorage.USER_GROUP_CURRENT_PREFIX + account);
        JSONArray jsonArray = (JSONArray) JSONObject.parse(lastContact);
        if(jsonArray != null && !jsonArray.isEmpty()){
            resultList = JSONObject.parseArray(jsonArray.toJSONString(), ScAccountFindLastContactResultPojo.class);
        }

        serviceResult.setMessage(ServiceResult.SELECT_SUCCESS);
        serviceResult.setSuccess(Boolean.TRUE);
        serviceResult.setResult(resultList);
        return serviceResult;
    }

    /**
     * 获取供应商协同账号的近期联系人
     * @param account 账号
     * @return 返回查询结果
     */
    @Override
    public ServiceResult<List<ScAccountFindLastContactResultPojo>> findScRecentContact(String account) {
        List<ScAccountFindLastContactResultPojo> list = new ArrayList<>();

        // 查询当前账号信息
        QueryWrapper<Account> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(AccountConstants.USERNAME_FIELD, account);
        List<Account> list1 = accountMapper.selectList(queryWrapper);
        if(list1 != null && list1.size() > 0){
            Account account1 = list1.get(0);
            Integer integration = account1.getIntegration();

            // 采购
            if(integration.intValue() == AccountIntegrationEnum.ERP_CORRELATION.getCode().intValue()){
                // 查询采购的最近联系人数据
                List<ScAccountFindLastContactResultPojo> lastContact = accountMapper.getScRecentContact(account);

                for (ScAccountFindLastContactResultPojo scAccountFindLastContactResultPojo : lastContact) {
                    // 处理消息内容
                    handleScContext(scAccountFindLastContactResultPojo, account);
                    list.add(scAccountFindLastContactResultPojo);
                }
            }

            // 供应商协同账号
            if(integration.intValue() == AccountIntegrationEnum.SC_CORRELATION.getCode().intValue()){
                // 获取与采购的最近联系信息
                ScAccountFindLastContactResultPojo scAccountFindLastContactResultPojo = accountMapper.selectScSaleLastContactInfo(account1.getId());
                // 处理消息内容
                handleScContext(scAccountFindLastContactResultPojo, account);

                // 查询上次评分时间
                Date date = customerServiceScoreMapper.queryLastScoreTime(account1.getId());
                scAccountFindLastContactResultPojo.setLastScoreTime(date);

                list.add(scAccountFindLastContactResultPojo);

                // 查询与系统账号的最近联系信息
                String systemAccount = systemConfig.getAccount();
                ScAccountFindLastContactResultPojo pojo = accountMapper.selectScSystemLastContactInfo(account1.getUsername(), systemAccount);
                list.add(pojo);
            }
        }

        ServiceResult<List<ScAccountFindLastContactResultPojo>> serviceResult = new ServiceResult<>();
        serviceResult.setSuccess(Boolean.TRUE);
        serviceResult.setMessage(ServiceResult.SELECT_SUCCESS);
        serviceResult.setResult(list);
        return serviceResult;
    }

    /**
     * 获取最近一对一、群组的联系人数据。按置顶顺序降序排列，按最后聊天时间降序排列。显示未读消息数量
     * @param account 账号
     * @return 返回近期的联系人数据
     */
    @Override
    public ServiceResult<List<AccountGroupLastContactPojo>> findLastContact(String account) {
        ServiceResult<List<AccountGroupLastContactPojo>> serviceResult = new ServiceResult<>();
        List<AccountGroupLastContactPojo> resultList = new ArrayList<>();

        // 查询一对一聊天最近联系人数据
        List<AccountGroupLastContactPojo> chatPairList = getChatPairLastContact(account);
        if(chatPairList != null && chatPairList.size() > 0){
            resultList.addAll(chatPairList);
        }

        // 查询默认群组最近联系数据
        List<AccountGroupLastContactPojo> groupList = getGroupLastContact(account);
        if(groupList != null && groupList.size() > 0){
            resultList.addAll(groupList);
        }

        // 查询自定义群组最近联系数据
        List<AccountGroupLastContactPojo> userGroupList = getUserGroupLastContact(account);
        if(userGroupList != null && userGroupList.size() > 0){
            resultList.addAll(userGroupList);
        }

        // 按最近联系时间排序
        if(resultList != null && resultList.size() > 1){
            // 根据最近联系时间排序
            resultList.sort((o1, o2) -> {
                if (o1.getLastMessageTime() != null && o2.getLastMessageTime() != null) {
                    return o2.getLastMessageTime().compareTo(o1.getLastMessageTime());
                } else {
                    return o1.getLastMessageTime() == null ? 1 : -1;
                }
            });

            // 根据置顶时间排序
            resultList.sort((o1, o2) -> {
                if (o1.getToppingTime() != null && o2.getToppingTime() != null) {
                    return o2.getToppingTime().compareTo(o1.getToppingTime());
                } else if(o1.getToppingTime() != null && o2.getToppingTime() == null) {
                    return 1;
                } else if(o1.getToppingTime() == null && o2.getToppingTime() != null) {
                    return -1;
                }else {
                    return 0;
                }
            });

            // 处理置顶数据，按最近联系时间排序
            List<AccountGroupLastContactPojo> toppingList = new ArrayList<>();
            List<AccountGroupLastContactPojo> simpleList = new ArrayList<>();
            for (AccountGroupLastContactPojo accountGroupLastContactPojo : resultList){
                if(accountGroupLastContactPojo.getToppingTime() != null){
                    toppingList.add(accountGroupLastContactPojo);
                }else{
                    simpleList.add(accountGroupLastContactPojo);
                }
            }

            resultList = new ArrayList<>();

            // 按最近联系时间倒序对置顶数据进行排序
            if(toppingList.size() > 0){
                toppingList.sort((o1, o2) -> {
                    Date largeTime;

                    Date toppingTime1 = o1.getToppingTime();
                    Date toppingTime2 = o2.getToppingTime();

                    if(toppingTime1.compareTo(toppingTime2) > 0){
                        largeTime = toppingTime1;
                    }else{
                        largeTime = toppingTime2;
                    }

                    Date lastMessageTime1 = o1.getLastMessageTime();
                    if(lastMessageTime1 != null){
                        if(lastMessageTime1.compareTo(largeTime) > 0){
                            largeTime = lastMessageTime1;
                        }
                    }

                    Date lastMessageTime2 = o2.getLastMessageTime();
                    if(lastMessageTime2 != null){
                        if(lastMessageTime2.compareTo(largeTime) > 0){
                            largeTime = lastMessageTime2;
                        }
                    }

                    if(largeTime.compareTo(toppingTime1) == 0 || (lastMessageTime1 != null && largeTime.compareTo(lastMessageTime1) == 0)){
                        return -1;
                    }

                    if(largeTime.compareTo(toppingTime2) == 0 || (lastMessageTime2 != null && largeTime.compareTo(lastMessageTime2) == 0)){
                        return 1;
                    }
                    return 0;
                });
                resultList.addAll(toppingList);
            }


            if(simpleList.size() > 0){
                resultList.addAll(simpleList);
            }
        }

        serviceResult.setMessage(ServiceResult.SELECT_SUCCESS);
        serviceResult.setSuccess(Boolean.TRUE);
        serviceResult.setResult(resultList);
        return serviceResult;
    }

    /**
     * 将用户最近联系人的数据导入redis
     * @return 返回导入结果
     */
    @Override
    public ServiceResult<Boolean> importCurrentIntoRedis(List<String> accountList) {
        // 将用户最近联系人的数据导入redis
        if (accountList != null && accountList.size() > 0) {
            for (String userName : accountList) {
                addCurrentDataToRedis(userName);
            }
        }

        ServiceResult<Boolean> returnResult = new ServiceResult<>();
        returnResult.setMessage(ServiceResult.SYNC_SUCCESS);
        returnResult.setSuccess(Boolean.TRUE);
        returnResult.setResult(Boolean.TRUE);
        return returnResult;
    }

    /**
     * 导入最新的最近联系人数据
     * @param userName 用户名
     */
    @Override
    public ServiceResult<Boolean> insertUserCurrentDataToRedis(String userName) {
        addCurrentDataToRedis(userName);
        ServiceResult<Boolean> returnResult = new ServiceResult<>();
        returnResult.setMessage(ServiceResult.SYNC_SUCCESS);
        returnResult.setSuccess(Boolean.TRUE);
        returnResult.setResult(Boolean.TRUE);
        return returnResult;
    }

    /**
     * 添加UserGroup对象和RefUserGroupAccount对象，并返回新创建的群组的id
     * @param userGroupName
     * @param newMemberAccountIdList
     * @return
     */
    @Override
    public ServiceResult<Integer> saveUserGroupAndRefUserGroupAccount(String userGroupName, List<String> newMemberAccountIdList) {
        ServiceResult<Integer> serviceResult = new ServiceResult<>();

        // 向user_group表中插入数据
        UserGroup userGroup = new UserGroup();
        userGroup.setName(userGroupName);
        userGroupMapper.saveUserGroupReturnId(userGroup);

        // 向ref_user_group_account表中插入多条记录
        for (String account : newMemberAccountIdList) {
            if(account == null){
                log.info("accountId值为null,无法进行插入操作,跳过当前数据进行处理");
                continue;
            }

            RefUserGroupAccount refUserGroupAccount = new RefUserGroupAccount();
            refUserGroupAccount.setAccountId(account);
            refUserGroupAccount.setUserGroupId(userGroup.getId());
            refUserGroupAccount.setJoinGroupTime(new Date(System.currentTimeMillis()));

            log.info("根据id查询Account表数据,id=[{}]", account);
            Account theAccount = accountMapper.selectById(account);
            if(theAccount != null){
                refUserGroupAccount.setUsername(theAccount.getUsername());
            }else{
                log.info("查询Account表数据失败,id:[{}]不存在", account);
            }

            // 根据用户组id、账号id、姓名查询库中数据数量,判断库中是否已有当前数据
            int count = getUserGroupAccountCountBygroupAccountIdUsername(refUserGroupAccount.getUserGroupId(), refUserGroupAccount.getAccountId(), refUserGroupAccount.getUsername());
            if(count > 0){
                log.info("数据库中已有userGroupId=[{}],accountId=[{}],username=[{}]的记录,不进行插入操作",
                        refUserGroupAccount.getUserGroupId(), refUserGroupAccount.getAccountId(), refUserGroupAccount.getUsername());
                continue;
            }
            refUserGroupAccountMapper.insert(refUserGroupAccount);
        }

        // 从ref_user_group_account表中查找某一群组中的账号数量
        QueryWrapper<RefUserGroupAccount> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_group_id", userGroup.getId());
        Integer count = refUserGroupAccountMapper.selectCount(queryWrapper);

        // 更新ref_user_group_account表的membership字段
        userGroup.setMembership(count);
        userGroupMapper.updateById(userGroup);

        serviceResult.setMessage(ServiceResult.INSERT_SUCCESS);
        serviceResult.setSuccess(Boolean.TRUE);
        serviceResult.setResult(userGroup.getId());
        return serviceResult;
    }

    /**
     * 根据id查找Group对象
     *
     * @param userGroupId
     * @return
     */
    @Override
    public ServiceResult <UserGroup> findByRealId(Integer userGroupId) {
        ServiceResult <UserGroup> serviceResult = new ServiceResult<UserGroup>();
        UserGroup userGroup = userGroupMapper.findByRealId(userGroupId);

        serviceResult.setMessage(ServiceResult.SELECT_SUCCESS);
        serviceResult.setSuccess(Boolean.TRUE);
        serviceResult.setResult(userGroup);
        return serviceResult;
    }

    /**
     * 根据自定义群组Id获取自定义群组中在线人数
     * @param userGroupId 自定义群组id
     * @return 在线人员数量
     */
    @Override
    public ServiceResult<Long> getUserNumberOnline(String userGroupId) {
        ServiceResult<Long> serviceResult = new ServiceResult<Long>();
        WebSocketHandler webSocketHandler = HandlerHelper.getWebSocketHandler();
        log.info("根据userGroupId:[{}]查询redis中键:[{}]的数量,数量即为当前自定义群组在线人数", userGroupId, RedisStorage.ONLINE_USER_GROUP_MAP + ":" + userGroupId);
        Long redisKeySize = webSocketHandler.getRedisKeySize(RedisStorage.ONLINE_USER_GROUP_MAP + ":" +  userGroupId);
        log.info("根据userGroupId:[{}]查询redis中键:[{}]的数量成功,当前自定义群组在线人数为:[{}]", userGroupId, RedisStorage.ONLINE_USER_GROUP_MAP + ":" + userGroupId, redisKeySize);
        serviceResult.setMessage(ServiceResult.SELECT_SUCCESS);
        serviceResult.setSuccess(Boolean.TRUE);
        serviceResult.setResult(redisKeySize);
        return serviceResult;
    }

    /**
     * 根据群组id修改用户自定义群组记录
     * @param userGroupVo 自定义群组内容
     */
    @Override
    public ServiceResult<Integer> updateUserGroup(UserGroupVo userGroupVo){
        ServiceResult<Integer> serviceResult = new ServiceResult<>();

        UpdateWrapper<UserGroup> userGroupUpdateWrapper = new UpdateWrapper<>();
        userGroupUpdateWrapper.eq(Constants.ID, userGroupVo.getId());
        UserGroup userGroup = new UserGroup();
        userGroup.setName(userGroupVo.getName());
        userGroup.setMembership(userGroupVo.getMembership());
        int update = userGroupMapper.update(userGroup, userGroupUpdateWrapper);
        if(update > 0){
            log.info("修改自定义群组名称为:[{}]成功,自定义群组id为:[{}]", userGroupVo.getName(), userGroupVo.getId());
        }

        serviceResult.setMessage(ServiceResult.SELECT_SUCCESS);
        serviceResult.setSuccess(Boolean.TRUE);
        serviceResult.setResult(update);
        return serviceResult;
    }

    /**
     * 添加最近联系人数据到redis
     * @param userName 用户名
     */
    private void addCurrentDataToRedis(String userName) {
        QueryWrapper<Account> queryWrapper = new QueryWrapper<>();
        List<Account> list = accountMapper.selectList(queryWrapper);
        if(list != null && list.size() > 0){
            Account account = list.get(0);
            Integer integration = account.getIntegration();
            // erp账号
            if(integration == null || integration.intValue() == AccountIntegrationEnum.ERP_CORRELATION.getCode().intValue()){
                ServiceResult<List<AccountGroupLastContactPojo>> lastContact = findLastContact(userName);
                redisManager.set(RedisStorage.USER_GROUP_CURRENT_PREFIX + userName, JSON.toJSONString(lastContact.getResult()));
            }
            // 供应商协同账号
            if(integration != null && integration.intValue() == AccountIntegrationEnum.SC_CORRELATION.getCode().intValue()){
                ServiceResult<List<ScAccountFindLastContactResultPojo>> scRecentContact = findScRecentContact(userName);
                redisManager.set(RedisStorage.USER_GROUP_CURRENT_PREFIX + userName, JSON.toJSONString(scRecentContact.getResult()));
            }
        }
    }

    /**
     * 查询自定义群组最近联系数据
     * @param account 账号
     * @return 返回自定义群组最近联系数据
     */
    private List<AccountGroupLastContactPojo> getUserGroupLastContact(String account) {
        List<AccountGroupLastContactPojo> list = new ArrayList<>();
        List<GroupPojo> userGroupPojoList = userGroupMapper.findUserGroupInfos(account);
        // 补充自定义群组成员信息
        if(userGroupPojoList != null && userGroupPojoList.size() > 0){
            for(GroupPojo groupPojo : userGroupPojoList){

                // 处理默认群组消息内容
                groupPojo = handleGroupMessageContext(groupPojo, account);

                Date lastMessageTime = groupPojo.getLastMessageTime();
                Date contentInvisibleTime = groupPojo.getContentInvisibleTime();
                if(contentInvisibleTime != null && lastMessageTime != null && contentInvisibleTime.compareTo(lastMessageTime) > 0){
                    groupPojo.setLastMessage(null);
                    groupPojo.setLastMessageTime(contentInvisibleTime);
                    groupPojo.setLastMessageType(null);
                }

                Map<String, Object> map = new HashMap<>();
                map.put(Constants.USER_GROUP_ID, groupPojo.getId());
                List<Account> accounts = accountMapper.selectAccountByUserGroupParam(map);
                if(accounts != null && accounts.size() > 0){
                    groupPojo.setAccountList(accounts);
                }else{
                    groupPojo.setAccountList(new ArrayList<>());
                }
                AccountGroupLastContactPojo accountPojo = new AccountGroupLastContactPojo();
                BeanUtils.copyProperties(groupPojo, accountPojo);

                // 当最后一条消息时间超过可见时间，将最近消息字段置空
                Integer timeout = redisParamConfig.getTimeout();
                Date leftDateByTime = DateUtils.getLeftDateByTime(timeout);
                if(accountPojo.getLastMessageTime() != null && leftDateByTime.compareTo(accountPojo.getLastMessageTime()) > 0){
                    accountPojo.setLastMessage(null);
                    accountPojo.setLastMessageTime(leftDateByTime);
                    accountPojo.setLastMessageType(null);
                }

                // 最后一条消息时间为空时，返回与自定义群组的最近联系时间
                if(accountPojo.getLastMessageTime() == null){
                    accountPojo.setLastMessageTime(groupPojo.getLastContactTime());
                }

                list.add(accountPojo);
            }
        }
        return list;
    }

    /**
     * 查询默认群组最近联系数据
     * @param account 账号
     * @return 返回默认群组最近联系数据
     */
    private List<AccountGroupLastContactPojo> getGroupLastContact(String account) {
        List<AccountGroupLastContactPojo> list = new ArrayList<>();
        List<GroupPojo> groupPojoList = groupMapper.findLastContact(account);

        // 补充默认群组成员信息
        if(groupPojoList != null && groupPojoList.size() > 0){
            for(GroupPojo groupPojo : groupPojoList){

                // 处理默认群组消息内容
                groupPojo = handleGroupMessageContext(groupPojo, account);

                Date lastMessageTime = groupPojo.getLastMessageTime();
                Date contentInvisibleTime = groupPojo.getContentInvisibleTime();
                if(contentInvisibleTime != null && lastMessageTime != null && contentInvisibleTime.compareTo(lastMessageTime) > 0){
                    groupPojo.setLastMessage(null);
                    groupPojo.setLastMessageTime(contentInvisibleTime);
                    groupPojo.setLastMessageType(null);
                }

                Map<String, Object> map = new HashMap<>();
                map.put(Constants.GROUP_ID, groupPojo.getId());
                List<Account> accounts = accountMapper.selectAccountByGroupParam(map);
                if(accounts != null && accounts.size() > 0){
                    groupPojo.setAccountList(accounts);
                }else{
                    groupPojo.setAccountList(new ArrayList<>());
                }
                AccountGroupLastContactPojo accountPojo = new AccountGroupLastContactPojo();
                BeanUtils.copyProperties(groupPojo, accountPojo);

                // 当最后一条消息时间超过可见时间，将最近消息字段置空
                Integer timeout = redisParamConfig.getTimeout();
                Date leftDateByTime = DateUtils.getLeftDateByTime(timeout);
                if(accountPojo.getLastMessageTime() != null && leftDateByTime.compareTo(accountPojo.getLastMessageTime()) > 0){
                    accountPojo.setLastMessage(null);
                    accountPojo.setLastMessageTime(leftDateByTime);
                    accountPojo.setLastMessageType(null);
                }

                // 最后一条消息时间为空时，返回与默认群组的最近联系时间
                if(accountPojo.getLastMessageTime() == null){
                    accountPojo.setLastMessageTime(groupPojo.getLastContactTime());
                }

                // 组织机构的type需要特殊处理
                if(TreeNodeConstants.ORGANIZATION_GROUP_ID.equals(accountPojo.getGroupId())){
                    accountPojo.setType(4);
                }

                list.add(accountPojo);
            }
        }
        return list;
    }

    /**
     * 查询一对一最近聊天记录信息
     * @param account 账号
     * @return 返回一对一最近聊天记录信息
     */
    private List<AccountGroupLastContactPojo> getChatPairLastContact(String account) {
        List<AccountGroupLastContactPojo> list = new ArrayList<>();
        List<AccountFindLastContactResultPojo> lastContact = accountMapper.findLastContact(account);
        if (lastContact != null && !lastContact.isEmpty()){
            for (int i = 0; i < lastContact.size() ; i++) {
                AccountFindLastContactResultPojo accountFindLastContactResultPojo = lastContact.get(i);
                AccountGroupLastContactPojo accountPojo = new AccountGroupLastContactPojo();

                // 处理消息内容
                handleContext(accountFindLastContactResultPojo, account);

                BeanUtils.copyProperties(accountFindLastContactResultPojo, accountPojo);
                // 消息表内容类时间
                Date messageTime = accountFindLastContactResultPojo.getMessageTime();
                // 判断消息表时间是否小于内容不可见时间
                if(accountFindLastContactResultPojo.getContentInvisibleTime() != null && messageTime != null &&
                        accountFindLastContactResultPojo.getContentInvisibleTime().compareTo(messageTime) > 0){

                    // 最后一条消息时间为空时，返回最近联系时间
                    if(accountPojo.getLastMessageTime() == null){
                        accountPojo.setLastMessageTime(accountFindLastContactResultPojo.getLastContactTime());
                    }

                    list.add(accountPojo);
                    continue;
                }

                // 消息表时间不为空时返回消息表的信息
                if(messageTime != null){
                    accountPojo.setLastMessageTime(messageTime);
                    accountPojo.setLastMessageType(accountFindLastContactResultPojo.getMessageType());
                    accountPojo.setLastMessage(accountFindLastContactResultPojo.getMessageContent());
                }

                // 当内容不可见时间大于最近联系时间时，将最近联系时间信息置空
                if(accountPojo.getLastMessageTime() != null && accountFindLastContactResultPojo.getContentInvisibleTime() != null){
                    if(accountFindLastContactResultPojo.getContentInvisibleTime().compareTo(accountPojo.getLastMessageTime()) > 0){
                        accountPojo.setLastMessage(null);
                        accountPojo.setLastMessageTime(accountFindLastContactResultPojo.getContentInvisibleTime());
                        accountPojo.setLastMessageType(null);
                    }
                }

                // 当最后一条消息时间超过可见时间，将最近消息字段置空
                Integer timeout = redisParamConfig.getTimeout();
                Date leftDateByTime = DateUtils.getLeftDateByTime(timeout);
                if(accountPojo.getLastMessageTime() != null && leftDateByTime.compareTo(accountPojo.getLastMessageTime()) > 0){
                    accountPojo.setLastMessage(null);
                    accountPojo.setLastMessageTime(leftDateByTime);
                    accountPojo.setLastMessageType(null);
                }

                // 最后一条消息时间为空时，返回最近联系时间
                if(accountPojo.getLastMessageTime() == null){
                    accountPojo.setLastMessageTime(accountFindLastContactResultPojo.getLastContactTime());
                }

                list.add(accountPojo);
            }
        }

        return list;
    }

    /**
     * 处理供应商协同消息内容
     * @param scAccountFindLastContactResultPojo 供应商协同账号或采购获取近期的联系人结果pojo类
     * @param account 当前查询最近联系信息的账号
     */
    private ScAccountFindLastContactResultPojo handleScContext(ScAccountFindLastContactResultPojo scAccountFindLastContactResultPojo, String account) {
        String content = scAccountFindLastContactResultPojo.getMessageContent();
        if(!Strings.isNullOrEmpty(content) && scAccountFindLastContactResultPojo.getMessageType().intValue() == MessageType.SYS_MSG){
            String fromUserAccount = scAccountFindLastContactResultPojo.getFromUserAccount();
            if(!Strings.isNullOrEmpty(fromUserAccount) && account.equals(fromUserAccount)){
                String fromUserRealName = scAccountFindLastContactResultPojo.getFromUserRealName();
                if(!Strings.isNullOrEmpty(fromUserRealName)){
                    content = content.replaceAll(fromUserRealName, "你");
                }else{
                    content = content.replaceAll(scAccountFindLastContactResultPojo.getFromUserAccount(), "你");
                }

                scAccountFindLastContactResultPojo.setMessageContent(content);
            }
        }

        // 根据消息类型获取固定消息内容
        String fixMessage = getFixMessageByMessageType(scAccountFindLastContactResultPojo.getMessageType());
        if(!Strings.isNullOrEmpty(fixMessage)){
            scAccountFindLastContactResultPojo.setMessageContent(fixMessage);
        }

        // 消息表内容类时间
        Date messageTime = scAccountFindLastContactResultPojo.getMessageTime();

        // 判断消息表时间是否小于内容不可见时间
        if (scAccountFindLastContactResultPojo.getContentInvisibleTime() != null && messageTime != null &&
                scAccountFindLastContactResultPojo.getContentInvisibleTime().compareTo(messageTime) > 0) {

            // 最后一条消息时间为空时，返回最近联系时间
            if (scAccountFindLastContactResultPojo.getLastMessageTime() == null) {
                scAccountFindLastContactResultPojo.setLastMessageTime(scAccountFindLastContactResultPojo.getLastContactTime());
            }

            return scAccountFindLastContactResultPojo;
        }

        // 消息表时间不为空时返回消息表的信息
        if (messageTime != null) {
            scAccountFindLastContactResultPojo.setLastMessageTime(messageTime);
            scAccountFindLastContactResultPojo.setLastMessageType(scAccountFindLastContactResultPojo.getMessageType());
            scAccountFindLastContactResultPojo.setLastMessage(scAccountFindLastContactResultPojo.getMessageContent());
        }

        // 当内容不可见时间大于最近联系时间时，将最近联系时间信息置空
        if (scAccountFindLastContactResultPojo.getLastMessageTime() != null && scAccountFindLastContactResultPojo.getContentInvisibleTime() != null) {
            if (scAccountFindLastContactResultPojo.getContentInvisibleTime().compareTo(scAccountFindLastContactResultPojo.getLastMessageTime()) > 0) {
                scAccountFindLastContactResultPojo.setLastMessage(null);
                scAccountFindLastContactResultPojo.setLastMessageTime(scAccountFindLastContactResultPojo.getContentInvisibleTime());
                scAccountFindLastContactResultPojo.setLastMessageType(null);
            }
        }

        // 当最后一条消息时间超过可见时间，将最近消息字段置空
        Integer timeout = redisParamConfig.getTimeout();
        Date leftDateByTime = DateUtils.getLeftDateByTime(timeout);
        if (scAccountFindLastContactResultPojo.getLastMessageTime() != null && leftDateByTime.compareTo(scAccountFindLastContactResultPojo.getLastMessageTime()) > 0) {
            scAccountFindLastContactResultPojo.setLastMessage(null);
            scAccountFindLastContactResultPojo.setLastMessageTime(leftDateByTime);
            scAccountFindLastContactResultPojo.setLastMessageType(null);
        }

        // 最后一条消息时间为空时，返回最近联系时间
        if (scAccountFindLastContactResultPojo.getLastMessageTime() == null) {
            scAccountFindLastContactResultPojo.setLastMessageTime(scAccountFindLastContactResultPojo.getLastContactTime());
        }

        return scAccountFindLastContactResultPojo;
    }

    /**
     * 处理消息内容
     * @param accountFindLastContactResultPojo 获取近期的联系人结果pojo类
     * @param account 当前查询最近联系信息的账号
     */
    private void handleContext(AccountFindLastContactResultPojo accountFindLastContactResultPojo, String account) {
        String content = accountFindLastContactResultPojo.getMessageContent();
        if(!Strings.isNullOrEmpty(content) && accountFindLastContactResultPojo.getMessageType().intValue() == MessageType.SYS_MSG){
            String fromUserAccount = accountFindLastContactResultPojo.getFromUserAccount();
            if(!Strings.isNullOrEmpty(fromUserAccount) && account.equals(fromUserAccount)){
                String fromUserRealName = accountFindLastContactResultPojo.getFromUserRealName();
                if(!Strings.isNullOrEmpty(fromUserRealName)){
                    content = content.replaceAll(fromUserRealName, "你");
                }else{
                    content = content.replaceAll(accountFindLastContactResultPojo.getFromUserAccount(), "你");
                }

                accountFindLastContactResultPojo.setMessageContent(content);
            }
        }

        // 根据消息类型获取固定消息内容
        String fixMessage = getFixMessageByMessageType(accountFindLastContactResultPojo.getMessageType());
        if(!Strings.isNullOrEmpty(fixMessage)){
            accountFindLastContactResultPojo.setMessageContent(fixMessage);
        }
    }

    /**
     * 根据消息类型获取固定消息内容
     * @param messageType 消息类型
     * @return 返回固定消息内容
     */
    private String getFixMessageByMessageType(Integer messageType){
        if(messageType != null){
            // 公告栏提醒
            if(messageType.intValue() == MessageType.BULLETIN_BOARD_REMINDER.intValue()){
                return FixMessageContent.BULLETIN_BOARD_REMINDER_MSG;
            }

            // 二次比价任务提醒
            if(messageType.intValue() == MessageType.DOUBLE_PRICE_COMPARISON_TASK_NOTICE.intValue()){
                return FixMessageContent.DOUBLE_PRICE_COMPARISON_TASK_NOTICE_MSG;
            }

            // 销售订单推送失败
            if(messageType.intValue() == MessageType.SALES_ORDER_PUSH_FAIL.intValue()){
                return FixMessageContent.SALES_ORDER_PUSH_FAIL_MSG;
            }
        }
        return null;
    }

    /**
     * 处理默认群组消息内容
     * @param groupPojo 群组的pojo类
     * @param account 当前查询最近联系信息的账号
     */
    private GroupPojo handleGroupMessageContext(GroupPojo groupPojo, String account) {
        String lastMessage = groupPojo.getLastMessage();
        if(!Strings.isNullOrEmpty(lastMessage) && groupPojo.getLastMessageType().intValue() == MessageType.SYS_MSG){
            String fromUserAccount = groupPojo.getFromUserAccount();
            if(!Strings.isNullOrEmpty(fromUserAccount) && account.equals(fromUserAccount)){
                String fromUserRealName = groupPojo.getFromUserRealName();
                lastMessage = lastMessage.replaceAll(fromUserRealName, "你");
                groupPojo.setLastMessage(lastMessage);
            }
        }
        return groupPojo;
    }

    /**
     * 根据用户组id、账号id、姓名查询库中数据数量
     * @param groupId 用户组id
     * @param accountId 账号id
     * @param userName 姓名
     * @return 返回库中数据数量
     */
    private int getUserGroupAccountCountBygroupAccountIdUsername(Integer groupId, String accountId, String userName){
        log.info("根据userGroupId=[{}],accountId=[{}],username=[{}]查询数据库记录", groupId, accountId, userName);
        QueryWrapper<RefUserGroupAccount> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(Constants.USER_GROUP_ID_FIELD, groupId);
        queryWrapper.eq(Constants.ACCOUNT_ID_FIELD, accountId);
        queryWrapper.eq(Constants.USER_NAME, userName);
        return refUserGroupAccountMapper.selectCount(queryWrapper);
    }
}